package com.ndkj.blog.utils;

import com.ndkj.blog.constant.MailConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * @program: blog
 * @description: 邮件服务工具类
 * @author: liuyong
 * @create: 2022-05-05 17:03
 */
@Component
@Slf4j(topic = "com.blog.MailUtils")
public class MailUtils {

    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Async
    public void sendMail(String subject, String text, String mailTo) {
        sendMail(subject, text, MailConstant.MAIL_SEND_ACCOUNT_ADDRESS, mailTo);
    }

    @Async
    @Deprecated
    public void sendMail(String subject, String text, String mailFrom, String mailTo) {
        System.out.println(new Date() + "准备发送邮件......");
        //创建一个复杂的邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //用MimeMessageHelper帮助类来组装得到可编辑的邮件对象
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setSubject(subject);
            // 编辑好发送的信息
            // 编辑邮件文本信息。true意思为：开启HTML支持
            mimeMessageHelper.setText(text, true);
            //添加附件,linux服务器日志路径，本地测试请注释此语句
            // mimeMessageHelper.addAttachment(LogLocationConstant.MAIL_LOG_FILE_NAME, new File(LogLocationConstant.LOG_LOCATION));
            mimeMessageHelper.setTo(mailTo);
            mimeMessageHelper.setFrom(mailFrom);
        } catch (MessagingException e) {
            log.error("MailUtils发生异常");
            e.printStackTrace();
        }
        //发送邮件
        try {
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            log.error("邮件发送服务端处理异常");
            e.printStackTrace();
        }
        log.info("信息已发送至邮箱:{},{}", mailTo, text);
    }

}
